package com.zrf.gulimall.auth.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.zrf.gulimall.auth.utils.HttpUtils;
import com.zrf.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * todo 第三方登录后续完善
 * @Author zhanrf
 * @Date 2022/1/1 22:45
 */
@Controller
@RequestMapping("/auth")
public class AuthController {
	@GetMapping("/gitee/success")
	public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
		// 根据code码换取access_token
		Map<String, String> body = MapUtil.newHashMap();
		body.put("grant_type", "authorization_code");
		body.put("code", code);
		body.put("client_id", "860a0d583d72ed73016462f02878dc4e103e8fbb34382bd7e667e13bfa489899");
		body.put("client_secret", "cecf340d81efa2b19fdc5c639a4cb47e71b117288559fdb719c742ef5e522226");
		body.put("redirect_uri", "http://auth.gulimall.com/auth/gitee/success");
		HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), body, new HashMap<>());
		if (response.getStatusLine().getStatusCode() == 200) {
			// 获取到了access_token,转为通用社交登录对象
			String result = EntityUtils.toString(response.getEntity());
			SocialUser socialUser = JSON.parseObject(result, SocialUser.class);
			// todo 远程调用会员服务增加会员信息，并与第三方登录关联
			return "redirect:http://gulimall.com";
		}
		return "redirect:http://auth.gulimall.com/login.html";
	}
}
